package cn.ld.exception.handler;

import cn.ld.exception.code.ErrorCode;
import cn.ld.exception.exception.BusinessException;
import cn.ld.util.AjaxResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 让controller所有的方法都走这儿处理异常
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理自定义的Business异常
     * @param e
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    public AjaxResult businessExceptionHandler(BusinessException e){
        //打印一下该异常
        e.printStackTrace();
        //处理最后的返回值
        return AjaxResult.me().setSuccess(false).setMessage(e.getMessage()).setCode(e.getErrorCode());
    }


    /**
     * 处理MethodArgumentNotValidException(参数自己检验)异常
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult methodArgumentNotValidException(MethodArgumentNotValidException e){
        e.printStackTrace();
        BindingResult bindingResult = e.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < fieldErrors.size(); i++) {
            FieldError error = fieldErrors.get(i);
            String message = error.getDefaultMessage();
            if (i==fieldErrors.size()-1){
                sb.append(message);
            }else {
                sb.append(message+",");
            }
        }

        return AjaxResult.me().setSuccess(false).setCode(ErrorCode.ERROR_CODE_400.getCode()).setMessage(sb.toString());
    }

    /**
     * 处理Exception
     */
    @ExceptionHandler(Exception.class)
    public AjaxResult exceptionHandle(Exception e){
      e.printStackTrace();
      return AjaxResult.me().setSuccess(false).setCode(ErrorCode.ERROR_CODE_500.getCode()).setMessage(ErrorCode.ERROR_CODE_500.getMessage());
    }
}
